package com.shawn.spring.boot.quartz.config;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import com.shawn.spring.boot.quartz.job.TestJob;
import javax.annotation.PostConstruct;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author shawn
 * @since 2020/8/25
 */
@Configuration
@Import(SchedulerConfig.class)
public class QuartzJobConfig {

  @Value("${spring.quartz.job.cron}")
  private String cron;

  @Autowired private Scheduler scheduler;

  @PostConstruct
  public void initDemoJob() throws Exception {
    JobDetail job =
        newJob(TestJob.class)
            .withIdentity(TestJob.class.getName() + "_job", "test_job")
            .storeDurably()
            .build();
    Trigger trigger =
        newTrigger()
            .withIdentity(TestJob.class.getName() + "_trigger", "test_trigger")
            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
            .forJob(job)
            .build();
    scheduler.scheduleJob(job, trigger);
  }
}
